#include <linux/version.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include "../Include/UDPSocket.h"
#include "../Include/SocketUtil.h"

CUDPSocket::CUDPSocket()
{
}

CUDPSocket::CUDPSocket(Int32 nFD) : CInetSocket(nFD)
{
}

CUDPSocket::~CUDPSocket()
{
}

Bool CUDPSocket::Create(EAddressFamily af)
{
    int theAf = AF_INET;
    if (af == AF_IPv6)
    {
        theAf = AF_INET6;
    }

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 22)
	m_nFD = socket(theAf, SOCK_DGRAM|SOCK_CLOEXEC, 0);
#else
    m_nFD = socket(theAf, SOCK_DGRAM, 0);
#endif

    if (af == AF_IPv6)
    {
        int on = 1;
        setsockopt(m_nFD, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
    }

	return (m_nFD != -1);
}

Int32 CUDPSocket::RecvFrom(LPSTR szBuff, Int32 nLen, CSocketAddr &address)
{
	return SocketUtil::RecvFrom(m_nFD, szBuff, nLen, address);
}

Int32 CUDPSocket::SendTo(LPCSTR lpszBuff, Int32 nLen, const CSocketAddr &address)
{
	return SocketUtil::SendTo(m_nFD, lpszBuff, nLen, address);
}
